package com.qiaoba.auth.filter;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.auth.constant.SecurityConstant;
import com.qiaoba.api.auth.utils.JwtUtil;
import com.qiaoba.auth.service.OnlineUserService;
import com.qiaoba.common.base.context.UserInfoContext;
import com.qiaoba.common.base.order.GlobalFilterOder;
import com.qiaoba.nosql.redis.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 在线用户过滤器
 *
 * @author ailanyin
 * @date 2023-09-10 19:55:20
 */
@Component
@Order(GlobalFilterOder.ONLINE_USER_FILTER)
@RequiredArgsConstructor
public class OnlineUserFilter extends OncePerRequestFilter {

    private final RedisService redisService;
    private final OnlineUserService onlineUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String token = JwtUtil.getToken(request, true);
            if (StrUtil.isNotBlank(token)) {
                token = redisService.getObject(SecurityConstant.LOGIN_USER_TOKENS_REDIS_KEY + token, String.class);
                if (StrUtil.isNotBlank(token)) {
                    // 设置userId
                    UserInfoContext.setUserId(getUserId(token));
                    // 设置username
                    UserInfoContext.setUsername(getUsername(token));
                    // 设置deviceSn
                    UserInfoContext.setDeviceSn(getDeviceSn(token));
                    // 设置用户姓名
                    UserInfoContext.setNickname(getNickname(token));
                    // 处理后续逻辑
                    after(request);
                }
            }
            filterChain.doFilter(request, response);
        } finally {
            UserInfoContext.clear();
        }
    }

    private String getUserId(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_USER_ID).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private String getUsername(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_USERNAME).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private String getDeviceSn(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_DEVICE_SN).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private String getNickname(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_NICKNAME).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private void after(HttpServletRequest request) {
        String deviceSn = UserInfoContext.getDeviceSn();
        String username = UserInfoContext.getUsername();
        String nickname = UserInfoContext.getNickname();
        ThreadUtil.execAsync(() -> {
            // 刷新在线用户的在线时间
            onlineUserService.insert(request, deviceSn, username, nickname);
        });
    }
}
